<!-- 部门配置 -->
<template>
  <div class="dashboard-editor-container">
    <el-row style="background: #fff; padding: 16px 16px 0;">
      <div class="top topSubmitBtn">
        <el-button class="btn" type="primary" @click="addDepartment()">添加角色</el-button>
      </div>
      <div>
        <el-table border :data="tableData" style="width: 100%; margin: 15px 0" row-key="ID" default-expand-all
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
          <el-table-column prop="date" type="index" label="序号" width="80"></el-table-column>
          <el-table-column prop="Role" label="角色名称" width="150" show-overflow-tooltip></el-table-column>
          <el-table-column prop="Right" label="角色权限" width="350" show-overflow-tooltip>
            <template slot-scope="{ row }">
              {{
                row.Right
                  .filter(item => mapping.some(m => m.Class === item.Class))
                  .map(item => item.Class)
              .join(', ')
              }}
            </template>
          </el-table-column>
          <el-table-column prop="Inner" label="内置角色" width="100" show-overflow-tooltip>
            <template slot-scope="{row}">
              <span>{{ row.Inner === 1 ? '否' : '是' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="Descp" label="角色备注" show-overflow-tooltip></el-table-column>
          <el-table-column label="操作" fixed="right" width="180px">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" @click="handleEdit(scope.row)" :disabled="scope.row.Inner !== 1" >修改</el-button>
              <el-button size="mini" type="danger" @click="handleDelete(scope.row)" :disabled="scope.row.Inner !== 1" >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-row>
    <el-dialog top="5vh" :close-on-click-modal="false" :close-on-press-escape=false
      :title="Action === 1 ? '添加角色' : '修改角色'" :visible.sync="dialogVisible" v-el-drag-dialog width="600px">
      <el-form label-width="100px" :model="departForm" :rules="rules" ref="departForm">
        <el-form-item label='角色名称:' prop="Role">
          <el-input v-model.trim="departForm.Role" :disabled="Action === 2 ? true : false" maxlength="16"></el-input>
        </el-form-item>
        <el-form-item label='角色备注:' prop="Descp">
          <el-input v-model.trim="departForm.Descp" type="textarea" :rows="2" maxlength="16"></el-input>
        </el-form-item>
        <el-form-item label='角色权限:' prop="Right">
          <el-tree ref="tree" :data="CustomerList" v-model="departForm.Right" accordion show-checkbox node-key="ID"
            :default-expanded-keys="[0]" :props="{ multiple: true, label: 'Class', value: 'ID' }">
          </el-tree>
          <!-- <el-cascader-panel
            style="width: 100%;"
            v-model="departForm.Right"
            :props="{ multiple: true, emitPath: true, checkStrictly: false, label:'permission', value: 'permission' }"
            :options="roleList"
            @change="handleChange">
          </el-cascader-panel> -->
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit()">确 定</el-button>
        <el-button type="info" @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { connrequest } from "@/api/firstPage";
import { treeing, getTreeData } from "@/utils/index.js";
import { Material_URLS } from "./api/request.js";
import { noTokenRequest } from "@/api/material";
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
export default {
  directives: { elDragDialog },
  computed: {
    ...mapGetters([
      'permission_routes'
    ])
  },
  data() {
    return {
      dialogVisible: false,
      Action: 1,
      departForm: {},
      roleList: [],
      tableData: [],
      CustomerList: [
        {
          Class: "所有知识库",
          ID: 0,
          children: []
        }
      ],
      mapping: [],
      rules: {
        Role: [
          { required: true, message: '角色名称不能为空' }
        ],
        Role: [
          { required: true, message: '角色权限不能为空' }
        ]
      }
    };
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.getData()
    this.getKnowledgeMaterial()
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
  },
  methods: {
    async getData() {
      const res = await connrequest('GetEmployeeRole')
      this.tableData = res.Data
    },
    async getKnowledgeMaterial() {
      const res = await noTokenRequest(Material_URLS.getClassify);
      if (res.Status.StatusCode === 0) {
        this.CustomerList[0].children = this.buildTree(res.Data);
        this.mapping = res.Data;
      }
    },
    // 将获取到的分类信息转化成树状结构
    buildTree(data) {
      const map = {};
      const roots = [];
      // 初始化每个节点的 Children 数组
      data.forEach((item) => {
        map[item.ID] = { ...item, children: [] };
      });
      // 构建树关系
      data.forEach((item) => {
        if (item.ParentID === 0) {
          roots.push(map[item.ID]);
        } else {
          if (map[item.ParentID]) {
            map[item.ParentID].children.push(map[item.ID]);
          }
        }
      });
      return roots;
    },
    // 将树结构数据转换成级联选择器要展示的数据
    transformData(data) {
      return data.map((item) => ({
        value: item.ID,
        label: item.Class,
        children: item.children && item.children.length ? this.transformData(item.children) : null
      }));
    },
    handleChange(row) {
    },
    addDepartment() {
      this.Action = 1
      this.departForm = {}
      this.$nextTick(() => {
        this.$refs['departForm'].clearValidate()
        this.$refs.tree.setCheckedKeys([]);
      })
      this.dialogVisible = true
    },
    handleEdit(item) {
      this.Action = 2
      this.departForm = { ...item }
      const Right = this.departForm.Right.map(item => item.ID)
      this.$nextTick(() => {
        this.$refs.tree.setCheckedKeys(Right);
      })
      this.dialogVisible = true
    },
    async submit() {
      let arr = [...this.tableData]
      this.$refs['departForm'].validate(async (valid) => {
        if (valid) {
          let RightList = this.mapping.filter(item => [...new Set(this.$refs.tree.getCheckedKeys())].includes(item.ID))
          if (this.Action === 1) {
            if (this.tableData.findIndex(role => role.Role === this.departForm.Role) !== -1) {
              this.$message.error('该角色名称已经存在')
              return false
            }
            arr.push(
              {
                Inner: 1,
                Role: this.departForm.Role,
                Right: RightList,
                Descp: this.departForm.Descp
              }
            )
          } else if (this.Action === 2) {
            arr.forEach(item => {
              if (item.Role === this.departForm.Role) {
                item.Inner = this.departForm.Inner
                item.Role = this.departForm.Role
                item.Right = RightList
                item.Descp = this.departForm.Descp
              }
              return item
            })
          }
          const data = {
            Data: [...arr]
          }
          const res = await connrequest('SetEmployeeRole', data)
          if (res.Status.StatusCode === 0) {
            this.$message({
              type: 'success',
              message: this.Action === 1 ? '角色添加成功' : '角色修改成功'
            });
            this.getData()
            this.dialogVisible = false
          }
        }
      })
    },
    async handleDelete(item) {
      const res = await connrequest('GetEmployee')
      let UserList = res.Data
      if (UserList.findIndex(user => user.Role === item.Role) !== -1) {
        this.$message.error('该角色已被用户使用，禁止删除')
        return false
      }
      if (item.Inner === 0) {
        this.$message.error('该角色为内置角色，禁止删除')
        return false
      }
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let arr = this.tableData.filter(deleteItem => deleteItem.Role !== item.Role)
        let data = {
          Data: arr
        }
        const res = await connrequest('SetEmployeeRole', data)
        if (res.Status.StatusCode === 0) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.getData()
          this.dialogVisible = false
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    }
  }
};
</script>
<style scoped lang='scss'>
/* @import url(); 引入css类 */
.top {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>